package ru.gelin.android.multiplier;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;

public class MainActivity extends Activity {

    OperationsHistory history;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.history = new OperationsHistory(this);

        ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);

        ActionBar.Tab tab = actionBar.newTab()
                .setText(R.string.calc_tab)
                .setTabListener(new TabListener<CalcFragment>(this, "calc", CalcFragment.class));
        actionBar.addTab(tab);

        tab = actionBar.newTab()
                .setText(R.string.history_tab)
                .setTabListener(new TabListener<HistoryFragment>(this, "history", HistoryFragment.class));
        actionBar.addTab(tab);
    }

    public OperationsHistory getHistory() {
        return this.history;
    }

    private class TabListener<F> implements ActionBar.TabListener {

        private Fragment fragment;
        private final Activity activity;
        private final String tag;
        private Class<F> clazz;

        public TabListener(Activity activity, String tag, Class<F> clazz) {
            this.activity = activity;
            this.tag = tag;
            this.clazz = clazz;
        }

        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
            if (this.fragment == null) {
                this.fragment = Fragment.instantiate(this.activity, this.clazz.getName());
                ft.add(android.R.id.content, this.fragment, this.tag);
            } else {
                ft.attach(this.fragment);
            }
        }

        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
            if (this.fragment != null) {
                ft.detach(this.fragment);
            }
        }

        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
            // User selected the already selected tab. Usually do nothing.
        }

    }

}
